﻿using SelfMadeMillionaire.Web.Infrastructure.ViewModels.ContactUs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Recaptcha;
using SelfMadeMillionaire.Core;
using System.Configuration;
using SelfMadeMillionaire.Core.Services;

namespace SelfMadeMillionaire.Web.Infrastructure.Controllers
{
	public class ContactUsController : BaseController
	{
		readonly IEmailService _emailService;

		public ContactUsController(IEmailService emailService)
		{
			_emailService = emailService;
		}

		[HttpGet]
		public ActionResult Index(string statusMessage)
		{
		    var model = new ContactUsViewModel();
		    if (!String.IsNullOrEmpty(statusMessage))
		    {
		        model.SendStatusMessage = statusMessage;
		    }
			return View(model);
		}

		[RecaptchaControlMvc.CaptchaValidator]
		[HttpPost]
		public ActionResult Index(ContactUsViewModel model, bool captchaValid, string captchaErrorMessage)
		{
            ClearProductTypeInSession();

			if (ModelState.IsValid)
			{
			    if (!captchaValid)
                {
                    ModelState.AddModelError("recaptcha", captchaErrorMessage);
                    return View(model);
                }

                string paramName = string.Format("DepartmentEmail{0}", model.Department.ToString());
                string adminEmail = ConfigurationManager.AppSettings[paramName];
                
				string body = string.Format("First Name: {0}<br /> Last Name: {1}<br /> Email: {2}<br /> Phone: {3}<br /> Message: {4}", model.FirstName, model.LastName, model.Email, model.Phone, model.Comments);
                                
                if (_emailService.SendAlerts(adminEmail, "Request from Contact page", body, model.Email))
                {
                    model.SendStatusMessage = "Message Sent";
                    return RedirectToAction("Index", new {statusMessage = model.SendStatusMessage});
                }
                else
                    model.SendStatusMessage = "Unexpected Error, the message has not been sent. We are sorry for the inconvenience.";
			}

			return View(model);
		}
	}
}
